package com.hzcx.app.simplechat.ui.chat.adapter;

import android.graphics.drawable.AnimationDrawable;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.Nullable;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.chad.library.adapter.base.util.MultiTypeDelegate;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMMessage;
import com.hyphenate.chat.EMVoiceMessageBody;
import com.hyphenate.util.DateUtils;
import com.hyphenate.util.EMLog;
import com.hzcx.app.simplechat.MyApplication;
import com.hzcx.app.simplechat.R;
import com.hzcx.app.simplechat.chat.interfaces.OnChatMessageListener;
import com.hzcx.app.simplechat.chat.util.EaseChatRowVoicePlayer;
import com.hzcx.app.simplechat.ui.chat.bean.ChatHistoryBean;
import com.hzcx.app.simplechat.ui.user.bean.UserInfoBean;
import com.hzcx.app.simplechat.util.ClickableSpanTextView;
import com.hzcx.app.simplechat.util.TextHttpUtil;
import com.hzcx.app.simplechat.util.UserInfoUtil;
import com.hzcx.app.simplechat.util.glide.GlideUtils;
import com.hzcx.app.simplechat.util.toast.ToastUtils;

import java.io.File;
import java.util.Date;
import java.util.List;

public class ChatHistoryAdapter extends BaseQuickAdapter<ChatHistoryBean, BaseViewHolder> {

    private static final int TYPE_DEFAULT = 0;
    private static final int TYPE_SEND_TEXT = 1;
    private static final int TYPE_RECEIVE_TEXT = 2;
    private static final int TYPE_SEND_IMAGE = 3;
    private static final int TYPE_RECEIVE_IMAGE = 4;
    private static final int TYPE_SEND_VOICE = 5;
    private static final int TYPE_RECEIVE_VOICE = 6;
    private static final int TYPE_SEND_LOCATION = 7;
    private static final int TYPE_RECEIVE_LOCATION = 8;
    private static final int TYPE_SEND_CUSTOM_SHARE = 9;
    private static final int TYPE_RECEIVE_CUSTOM_SHARE = 10;
    private static final int TYPE_RECALL = 11;
    private static final int TYPE_BLACK = 12;
    private static final int TYPE_DELETE = 13;
    private static final int TYPE_CUSTOM_ASSISTANT = 14;
    private static final int TYPE_CUSTOM_NOTICE = 15;
    private static final int TYPE_CUSTOM_IMAGE_SEND = 16;
    private static final int TYPE_CUSTOM_IMAGE_RECEIVE = 17;

    private static final int SEND_TEXT = R.layout.rv_item_chat_message_txt_send;
    private static final int RECEIVE_TEXT = R.layout.rv_item_chat_message_txt_receive;
    private static final int SEND_IMAGE = R.layout.rv_item_chat_message_img_send;
    private static final int RECEIVE_IMAGE = R.layout.rv_item_chat_message_img_recieive;
    private static final int SEND_VOICE = R.layout.rv_item_chat_message_voice_send;
    private static final int RECEIVE_VOICE = R.layout.rv_item_chat_message_voice_receive;
    private static final int SEND_LOCATION = R.layout.rv_item_chat_message_location_send;
    private static final int RECEIVE_LOCATION = R.layout.rv_item_chat_message_location_receive;
    private static final int SEND_CUSTOM_SHARE = R.layout.rv_item_chat_message_share_user_send;
    private static final int RECEIVE_CUSTOM_SHARE = R.layout.rv_item_chat_message_share_user_receive;
    private static final int RECALL = R.layout.rv_item_chat_message_recall;
    private static final int BLACK = R.layout.rv_item_chat_message_black;
    private static final int DELETE = R.layout.rv_item_chat_message_delete;
    private static final int CUSTOM_ASSISTANT = R.layout.rv_item_chat_message_custom_assistant_receive;
    private static final int CUSTOM_NOTICE = R.layout.rv_item_chat_message_custom_notice;
    private static final int CUSTOM_IMAGE_SEND = R.layout.rv_item_chat_message_img_send;
    private static final int CUSTOM_IMAGE_RECEIVE = R.layout.rv_item_chat_message_img_recieive;
    private static final int DEFAULT = R.layout.rv_item_chat_message_default;

    private EaseChatRowVoicePlayer voicePlayer;
    private AnimationDrawable voiceAnimation;
    private OnImageOnClickListener messageListener;

    public ChatHistoryAdapter(@Nullable List<ChatHistoryBean> data) {
        super(data);
        setMultiTypeDelegate(new MultiTypeDelegate<ChatHistoryBean>() {
            @Override
            protected int getItemType(ChatHistoryBean chatHistoryBean) {
                if (chatHistoryBean.getType() == 1) {
                    return chatHistoryBean.getMember_id() == UserInfoUtil.getUserId() ? TYPE_SEND_TEXT : TYPE_RECEIVE_TEXT;
                } else if (chatHistoryBean.getType() == 2) {
                    return chatHistoryBean.getMember_id() == UserInfoUtil.getUserId() ? TYPE_SEND_IMAGE : TYPE_RECEIVE_IMAGE;
                } else if (chatHistoryBean.getType() == 3) {
                    return chatHistoryBean.getMember_id() == UserInfoUtil.getUserId() ? TYPE_SEND_LOCATION : TYPE_RECEIVE_LOCATION;
                } else if (chatHistoryBean.getType() == 4) {
                    return chatHistoryBean.getMember_id() == UserInfoUtil.getUserId() ? TYPE_SEND_VOICE : TYPE_RECEIVE_VOICE;
                }
                return TYPE_DEFAULT;
            }
        });

        getMultiTypeDelegate().registerItemType(TYPE_SEND_TEXT, SEND_TEXT)
                .registerItemType(TYPE_RECEIVE_TEXT, RECEIVE_TEXT)
                .registerItemType(TYPE_SEND_IMAGE, SEND_IMAGE)
                .registerItemType(TYPE_RECEIVE_IMAGE, RECEIVE_IMAGE)
                .registerItemType(TYPE_SEND_VOICE, SEND_VOICE)
                .registerItemType(TYPE_RECEIVE_VOICE, RECEIVE_VOICE)
                .registerItemType(TYPE_DEFAULT, DEFAULT)
                .registerItemType(TYPE_SEND_LOCATION, SEND_LOCATION)
                .registerItemType(TYPE_RECEIVE_LOCATION, RECEIVE_LOCATION)
                .registerItemType(TYPE_SEND_CUSTOM_SHARE, SEND_CUSTOM_SHARE)
                .registerItemType(TYPE_RECEIVE_CUSTOM_SHARE, RECEIVE_CUSTOM_SHARE)
                .registerItemType(TYPE_RECALL, RECALL)
                .registerItemType(TYPE_DELETE, DELETE)
                .registerItemType(TYPE_CUSTOM_ASSISTANT, CUSTOM_ASSISTANT)
                .registerItemType(TYPE_CUSTOM_NOTICE, CUSTOM_NOTICE)
                .registerItemType(TYPE_CUSTOM_IMAGE_SEND, CUSTOM_IMAGE_SEND)
                .registerItemType(TYPE_CUSTOM_IMAGE_RECEIVE, CUSTOM_IMAGE_RECEIVE)
                .registerItemType(TYPE_BLACK, BLACK);

        voicePlayer = EaseChatRowVoicePlayer.getInstance(MyApplication.getContext());
    }

    @Override
    protected void convert(BaseViewHolder helper, ChatHistoryBean item) {

        // 隐藏不需要的控件
        if (helper.getView(R.id.loading_view) != null) {
            helper.setVisible(R.id.loading_view, false);
        }
        if (helper.getView(R.id.iv_check_box) != null) {
            ImageView ivCheckBox = helper.getView(R.id.iv_check_box);
            ivCheckBox.setVisibility(View.GONE);
        }
        if (helper.getView(R.id.iv_read) != null) {
            helper.setVisible(R.id.iv_read, false);
        }
        if (helper.getView(R.id.iv_send_fail) != null) {
            helper.setVisible(R.id.iv_send_fail, false);
        }

        TextView tvDate = helper.getView(R.id.tv_date);
        if (tvDate != null) {
            if (helper.getAdapterPosition() == 0) {
                // 第0个表示肯定要展示时间
                tvDate.setVisibility(View.VISIBLE);
                tvDate.setText(DateUtils.getTimestampString(new Date(item.getCreatetime())));
            } else {
                ChatHistoryBean prevMessage = mData.get(helper.getAdapterPosition() - 1);
                if (prevMessage != null && DateUtils.isCloseEnough(item.getCreatetime(), prevMessage.getCreatetime())) {
                    tvDate.setVisibility(View.GONE);
                } else {
                    tvDate.setText(DateUtils.getTimestampString(new Date(item.getCreatetime())));
                    tvDate.setVisibility(View.VISIBLE);
                }
            }
        }

        // 设置通用的字段，头像，昵称等
        if (item.getMember_id() == UserInfoUtil.getUserId()) {
            // 发送方
            if (helper.getView(R.id.iv_head) != null) {
                try {
                    GlideUtils.loadImg(mContext, UserInfoUtil.getUserHead(), helper.getView(R.id.iv_head));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        } else {
            // 接收方
            if (helper.getView(R.id.iv_head) != null) {
                try {
                    GlideUtils.loadImg(mContext, item.getBymember().getAvatar(), helper.getView(R.id.iv_head));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

        if (item.getType() == 1) {
            // 文本消息
            ClickableSpanTextView tvContent = helper.getView(R.id.tv_content);
            tvContent.setText(TextHttpUtil.getInstance(mContext).identifyUrl(item.getMaincontent()));
        } else if (item.getType() == 2) {
            // 图片消息
            GlideUtils.loadChatImage(mContext, item.getUrlimage(), helper.getView(R.id.bivPic));
        } else if (item.getType() == 3) {
            // 语音消息
            helper.setText(R.id.tv_time, item.getVideo_length() + "\"");

            // 播放语音
            helper.getView(R.id.rl_voice_bg).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (voicePlayer.isPlaying()) {
                        // Stop the voice play first, no matter the playing voice item is this or others.
                        voicePlayer.stop();
                        // Stop the voice play animation.
                        stopVoicePlayAnimation(item, helper.getView(R.id.iv_voice));

                        // If the playing voice item is this item, only need stop play.
                        String playingId = voicePlayer.getCurrentPlayingId();
                        if (String.valueOf(item.getId()).equals(playingId)) {
                            return;
                        }
                    } else {
                        if (item.getMember_id() == UserInfoUtil.getUserId()) {
                            // Play the voice
                            playVoice(item, helper.getView(R.id.iv_voice));
                            // Start the voice play animation.
                            startVoicePlayAnimation(item, helper.getView(R.id.iv_voice));
                        } else {
                            play(item, helper.getView(R.id.iv_voice));
                        }
                    }
                }
            });
        }

        // 图片点击
        if (helper.getView(R.id.bivPic) != null) {
            if (messageListener == null) {
                return;
            }
            try {
                helper.getView(R.id.bivPic).setOnClickListener(view -> {
                    if (messageListener != null) {
                        messageListener.imageOnClick(helper.getAdapterPosition(),item.getUrlimage());
                    }
                });
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public interface OnImageOnClickListener{
        void imageOnClick(int pos,String url);
    }

    public void setOnImageOnClickListener(OnImageOnClickListener messageListener){
        this.messageListener=messageListener;
    }

    private void play(ChatHistoryBean message, ImageView ivVoice) {
//            ackMessage(message);
        playVoice(message, ivVoice);
        // Start the voice play animation.
        startVoicePlayAnimation(message, ivVoice);
    }

    private void playVoice(ChatHistoryBean msg, ImageView ivVoice) {
        voicePlayer.play(msg, mp -> {
            // Stop the voice play animation.
            stopVoicePlayAnimation(msg, ivVoice);
        });
    }

    public void startVoicePlayAnimation(ChatHistoryBean message, ImageView ivVoice) {
        if (message.getMember_id() != UserInfoUtil.getUserId()) {
            ivVoice.setImageResource(R.drawable.voice_from_icon);
        } else {
            ivVoice.setImageResource(R.drawable.voice_to_icon);
        }
        voiceAnimation = (AnimationDrawable) ivVoice.getDrawable();
        voiceAnimation.start();

        // Hide the voice item not listened status view.
//        if (message.direct() == EMMessage.Direct.RECEIVE) {
//            readStatusView.setVisibility(View.INVISIBLE);
//        }
    }

    public void stopVoicePlayAnimation(ChatHistoryBean message, ImageView ivVoice) {
        if (voiceAnimation != null) {
            voiceAnimation.stop();
        }

        if (message.getMember_id() != UserInfoUtil.getUserId()) {
            ivVoice.setImageResource(R.mipmap.ic_icon_chat_receive_voice_3);
        } else {
            ivVoice.setImageResource(R.mipmap.ic_icon_chat_send_voice_3);
        }
    }
}
